<?php

namespace App\Models\Crm;


class ArticleCategory extends Application
{
    //设置白名单
    protected $fillable = ['parent_id', 'name', 'thumb', 'is_show', 'description', 'sort_order', 'created_at', 'updated_at'];

    //设置别名
    protected $table = 'article_categories';

    /**
     * 获取一级分类下的二级分类
     */
    public function children()
    {
        return $this->hasMany('App\Models\Crm\ArticleCategory', 'parent_id', 'id');
    }

    /**
     * 用于表单{!! !!}
     */
    static function all_cates()
    {
        $cates = [];
        $parent = ArticleCategory::where('parent_id', 0)->sorted()->get();

        foreach ($parent as &$category) {
            $id = $category['id'];
            $children = ArticleCategory::where('parent_id', $id)->get();
            $cates[$category->name] = $children->pluck('name', 'id')->toArray();
        }
        return $cates;
    }

    /**
     * 查出一级分类下对应的二级分类
     */
    static function all_categories()
    {
        //一般方法
//        $categories = ArticleCategory::where('parent_id', 0)->Sorted()->get();
//        foreach ($categories as &$category) {
//            $category['children'] = ArticleCategory::where('parent_id', $category['id'])->get();
//        }

        //模型方法
        $categories = ArticleCategory::with('children')->where('parent_id', 0)->Sorted()->get();
        return $categories;
    }

    /**
     * 栏目分类下有很多文章
     */
    public function articles()
    {
        return $this->hasMany('App\Models\Crm\Article', 'category_id', 'id');
    }

    /**
     * 判断栏目分类下是否有文章
     */
    static function check_articles($id)
    {
        $category = self::with('articles')->find($id);
        if ($category->articles->isEmpty()) {
            return true;
        }
        return false;
    }


}
